package com.zxp.web.sys_user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxp.web.sys_user.entity.SysUser;
import com.zxp.web.sys_user.mapper.SysUserMapper;
import com.zxp.web.sys_user.service.SysUserService;
import com.zxp.web.sys_user_role.entity.SysUserRole;
import com.zxp.web.sys_user_role.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author MasterZ
 * @Date 2025/10/1 20:54
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(SysUser sysUser) {
        int insert = this.baseMapper.insert(sysUser);
        //设置用户角色
        if (insert > 0) {
            String[] split = sysUser.getRoleId().split(",");
            addUserRole(sysUser, split);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editUser(SysUser sysUser) {
        int insert = this.baseMapper.updateById(sysUser);
        //设置用户角色
        if (insert > 0) {
            String[] split = sysUser.getRoleId().split(",");
            //删除原来的角色
            deleteUserRole(sysUser.getUserId());
            //重新添加角色
            addUserRole(sysUser, split);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long userId) {
        //删除用户
        int i = this.baseMapper.deleteById(userId);
        if (i > 0) {
            //删除用户角色
            deleteUserRole(userId);
        }
    }

    @Override
    public SysUser loadUser(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getUsername, username);
        return this.getOne(queryWrapper);
    }

    /*
   通用方法：删除用户的角色
    */
    private void deleteUserRole(Long userId) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRole::getUserId, userId);
        sysUserRoleService.remove(queryWrapper);
    }

    /*
    通用方法：添加用户的角色
     */
    private void addUserRole(SysUser sysUser, String[] split) {
        if (split.length > 0) {
            List<SysUserRole> sysUserRoleList = new ArrayList<>();
            for (String roleId : split) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(sysUser.getUserId());
                userRole.setRoleId(Long.parseLong(roleId));
                sysUserRoleList.add(userRole);
            }
            sysUserRoleService.saveBatch(sysUserRoleList);
        }
    }
}